package com.tangly.module.controller;

import com.tangly.common.base.BaseController;
import com.tangly.common.exception.BusinessException;
import com.tangly.common.util.AuthUtil;
import com.tangly.common.utils.ValidateUtil;
import com.tangly.module.entity.SysRoleEntity;
import com.tangly.module.entity.UserAuthEntity;
import com.tangly.module.entity.UserInfoEntity;
import com.tangly.module.enums.UserSexEnum;
import com.tangly.module.enums.UserTypeEnum;
import com.tangly.module.service.ISysRoleService;
import com.tangly.module.service.IUserAuthService;
import com.tangly.module.service.IUserInfoService;
import com.tangly.module.vo.AppUserInfoVO;
import com.tangly.module.vo.AuthInfoVO;
import com.tangly.module.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping(value = "/app/user")
@Api(tags = "APP-用户个人")
@SuppressWarnings("unchecked")
@RestController
public class AppUserController extends BaseController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserAuthService userAuthService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @ApiOperation(value = "获取我的用户信息")
    @GetMapping("/my")
    @RequiresAuthentication
    public ResultVO<AppUserInfoVO> my() throws BusinessException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            AuthInfoVO userAuth = (AuthInfoVO) subject.getPrincipal();
            List<SysRoleEntity> sysRoleEntities = iSysRoleService.getSysRoleByUserId(userAuth.getUserId());
            List<String> roles = new ArrayList<>();
            for (SysRoleEntity sysRoleEntity : sysRoleEntities) {
                roles.add(sysRoleEntity.getRole());
            }
            if(ObjectUtils.isEmpty(userAuth.getUserId())){
                throw new BusinessException("请先完善用户信息");
            }
            UserInfoEntity userInfoEntity = userInfoService.selectByPrimaryKey(userAuth.getUserId());
            return new ResultVO<>(
                    AppUserInfoVO.builder()
                    .nickname(userInfoEntity.getNickname())
                    .avatar(userInfoEntity.getAvatar())
                    .build()
            );
        } else {
            throw new BusinessException("用户未登录");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查看指定用户信息")
    public ResultVO<AppUserInfoVO> getUserInfo(@PathVariable(value = "id") Long id) {
        UserInfoEntity entity = userInfoService.selectByPrimaryKey(id);

        AppUserInfoVO vo = AppUserInfoVO.convert(entity);

        return new ResultVO<>(vo);
    }


    @PostMapping
    @ApiOperation(value = "创建用户信息")
    @RequiresAuthentication
    public ResultVO<String> createUserInfo(String avatar,String nickname) {

        //        将用户信息和账号绑定关联
        AuthInfoVO authInfoVO = AuthUtil.getUserAuth();

        UserInfoEntity entity = new UserInfoEntity();

        // 手机号
        entity.setPhone(authInfoVO.getUsername());

        //时间戳后七位生成用户唯一code
        String timeStamp = String.valueOf(System.currentTimeMillis());
        timeStamp = timeStamp.substring(timeStamp.length() - 6, timeStamp.length());

        entity.setAvatar(avatar);
        entity.setCode(timeStamp);
        entity.setNickname(nickname);
        entity.setIsDelete(false);
        entity.setCreateTime(new Date());
        entity.setType(UserTypeEnum.REGISTER);
        entity.setSex(UserSexEnum.UNKNOW);
        ValidateUtil.validate(entity);
        userInfoService.insert(entity);

        UserAuthEntity authEntity = userAuthService.selectByPrimaryKey(authInfoVO.getUserAuthId());
        authEntity.setUserInfoId(entity.getId());
        userAuthService.updateByPrimaryKeySelective(authEntity);

        return ResultVO.success("操作成功");
    }

    @PatchMapping
    @ApiOperation(value = "修改用户信息")
    public ResultVO<String> updateUserInfo(String avatar,String nickname) {

        AuthInfoVO authInfoVO = AuthUtil.getUserAuth();

        UserInfoEntity entity = userInfoService.selectByPrimaryKey(authInfoVO.getUserId());
        entity.setAvatar(avatar);
        entity.setNickname(nickname);
        entity.setUpdateTime(new Date());

        ValidateUtil.validate(entity);
        userInfoService.updateByPrimaryKeySelective(entity);
        return ResultVO.success("操作成功");
    }


}
